package jwt

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

var signature = []byte("bankTokPart")

// Claims jwt加密生成token唯一码
type Claims struct {
	ID        int
	CreatTime string
	UserName  string
	jwt.RegisteredClaims
}

func GenerateToken(id int, CreateTime, UserName string) (tokenStr string, err error) {
	claims := Claims{
		ID:        id,
		CreatTime: CreateTime,
		UserName:  UserName,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(15 * time.Minute * time.Duration(1))), //过期时间
			IssuedAt:  jwt.NewNumericDate(time.Now()),                                          //签发时间
			NotBefore: jwt.NewNumericDate(time.Now()),                                          //生效时间
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenStr, err = token.SignedString(signature) //给token添加专属签名
	return tokenStr, err
}

// Secret 解析token签名
func Secret() jwt.Keyfunc {
	return func(token *jwt.Token) (interface{}, error) {
		return signature, nil
	}
}

// ParseToken 解析token
func ParseToken(tokenStr string) (*Claims, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenStr, claims, Secret())
	if err != nil {
		return nil, err
	}
	if !token.Valid {
		err = errors.New("解析token失败")
		return nil, err
	}
	return claims, err
}
